/*
 * BusinessExceptionHandler.java
 * business
 *
 * Created by ChenTao on 2017/2/28.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.utils;

import static com.yidiandao.business.utils.UIUtils.getPackageName;

import android.content.Intent;
import android.os.Build;
import android.os.Looper;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;

/** 应用Crash之后重启 */
public class BusinessExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "BusinessExceptionHandle";
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    //    private ICommonModel mModel;

    public BusinessExceptionHandler() {
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        // 汇报crash
        //        MobclickAgent.reportError(UIUtils.getContext(), ex);

        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            collectInfo(ex);
        }
    }

    private void collectInfo(Throwable ex) {
        StringBuilder info = new StringBuilder();
        // 获取版本名
        // 获取手机机型信息
        Class clazz = Build.class;
        // 获取所有的字段
        Field[] fields = clazz.getDeclaredFields();
        // 建立缓冲区存放数据
        for (Field field : fields) {
            String name = field.getName(); // 获取字段名
            try {
                if (name.equals("MANUFACTURER") || name.equals("MODEL")) {
                    Object value = field.get(null);
                    info.append(name + ":" + value + "\n");
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        // 拼接异常信息并上传到服务器
        appendErrorInfos(info, ex);
    }

    private void appendErrorInfos(StringBuilder info, Throwable ex) {
        try {
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            ex.printStackTrace(printWriter);
            printWriter.close();
            String result = writer.toString();

            info.append("VERSIONNAME :" + SysUtils.getAppVersionName(UIUtils.getContext()) + "\n")
                    .append(result);

            // 上传到服务器
            //            sendLog(info.toString());
            //重启应用
            reStartApp();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    /**
    //     * 向服务器发送错误信息
    //     */
    //    private void sendLog(String info) throws Exception {
    //        if (mModel == null)
    //            mModel = new CommonModel();
    //        mModel.sendErrorInfo(TAG, info);
    //    }

    /** 重启应用 */
    private void reStartApp() {
        //重启应用
        Intent launchIntentForPackage =
                UIUtils.getContext()
                        .getPackageManager()
                        .getLaunchIntentForPackage(getPackageName());
        UIUtils.getContext().startActivity(launchIntentForPackage);
        //保存友盟统计的信息
        UmengUtils.onKillProcess();
        // 杀掉自己的进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                UIUtils.showToast("很抱歉，程序出现异常，即将退出");
                Looper.loop();
            }
        }.start();

        return true;
    }
}
